import { createRouter, createWebHistory } from 'vue-router';
import type { Router, RouteRecordRaw } from 'vue-router';
import type { App } from 'vue';
import { APP_ENV_CONFIG, flattenRoutes } from '@/utils';
import { RootPageRoute, LoginRoute } from './base';
import { createRouterGuards } from './router-guards';
import type { IModuleType } from './types';

// 导入多个模块
const modules = import.meta.glob<IModuleType>('./modules/**/*.ts', { eager: true });
const routeModuleList: RouteRecordRaw[] = Object.keys(modules).reduce((list, key) => {
  const mod = modules[key].default ?? {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  return [...list, ...modList];
}, []);
const sortRouteCb = (a: any, b: any) => (a.meta?.sort ?? 0) - (b.meta?.sort ?? 0);
routeModuleList.sort(sortRouteCb);

// 权限路由
export const asyncRoutes = [...routeModuleList];
// 普通路由 无需权限
const constantRoutes = [RootPageRoute, LoginRoute];
export const flattenedRoutes = flattenRoutes([...constantRoutes, ...asyncRoutes]);
const router: Router = createRouter({
  history: createWebHistory(APP_ENV_CONFIG.baseUrl),
  routes: constantRoutes,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

export function setupRouter(app: App<Element>) {
  app.use(router);
  // 创建路由守卫
  createRouterGuards(router);
}

export default router;
